<script setup lang="ts">
	import { ref, onMounted } from 'vue'
	import { onLaunch } from '@dcloudio/uni-app'
	import { 
	  getBannerAPI, 
	  getPersonalizedAPI,
	  getTopPlaylistAPI,
	  getPersonalizedMvAPI 
	} from '@/apis/music.uts'
	import type { 
	  Banner, 
	  RootObject, 
	  Creator, 
	  Subscriber, 
	  Playlist, 
	  RootObjectList 
	} from '@/types/music.uts'
	import type { topListPlaylist } from '@/types/playlistDetail.uts'
	import type { Data } from '@/types/musicMV.uts'
	import { userUseStoreId } from '@/stores/musicStore.uts'
	import audioPlayer from '@/subPagesMusic/MusicHeader/index.uts';
	import searchVue from './components/search.vue'
	
	const userStore = userUseStoreId()
	
	// 数据初始化时明确类型
	const musicDataList = ref<Banner[]>([]) as any
	const RecommendtList = ref<Playlist[]>([]) as any
	const TogetherList = ref<topListPlaylist[]>([]) as any
	const OriginalList = ref<topListPlaylist[]>([]) as any
	const HotList = ref<topListPlaylist[]>([]) as any
	const RiseList = ref<topListPlaylist[]>([]) as any
	const AllList = ref<Record<string, topListPlaylist[]>>({}) as any
	const MvList = ref<Data[]>([]) as any
	const loading = ref(true)
	const error = ref(false)
	
	// 统一错误处理
	const handleRequest = async <T>(fn: () => Promise<T>): Promise<T | null> => {
	  try {
	    return await fn()
	  } catch (err) {
	    error.value = true
	    console.error('请求失败:', err)
	    uni.showToast({
	      title: '数据加载失败',
	      icon: 'none'
	    })
	    return null
	  }
	}
	
	// 生命周期处理
	onMounted(async () => {
	  await Promise.all([
	    getBanner(),
	    getPersonalized(),
	    getRanking(),
	    getMv()
	  ])
	  loading.value = false
	})
	
	// 获取轮播图数据
	const getBanner = async () => {
	  const res = await handleRequest(() => getBannerAPI(1)) as any
	  if (res?.banners) {
	    musicDataList.value = res.banners
	  }
	}
	
	// 获取推荐歌单
	const getPersonalized = async () => {
	  const res = await handleRequest(() => 
	    getPersonalizedAPI({
	      cat: "华语",
	      limit: 20,
	      offset: 0
	    }) as Promise<RootObjectList>
	  )
	  if (res?.playlists) {
	    RecommendtList.value = res.playlists
	  }
	}
	
	// 获取歌单排名
	const getRanking = async () => {
	  const [Hot, Original, Rise, Together] = await Promise.all([
	    handleRequest(() => getTopPlaylistAPI(3778678)),
	    handleRequest(() => getTopPlaylistAPI(2884035)),
	    handleRequest(() => getTopPlaylistAPI(19723756)),
	    handleRequest(() => getTopPlaylistAPI(3779629))
	  ]) as any
	
	  HotList.value = Hot?.playlist || []
	  OriginalList.value = Original?.playlist || []
	  RiseList.value = Rise?.playlist || []
	  TogetherList.value = Together?.playlist || []
	
	  AllList.value = {
	    '热歌榜': HotList.value,
	    '原创榜': OriginalList.value,
	    '飙升榜': RiseList.value,
	    '新歌榜': TogetherList.value
	  }
	}
	
	// 获取MV
	const getMv = async () => {
	  const res = await handleRequest(getPersonalizedMvAPI) as any
	  if (res?.data) {
	    MvList.value = res.data
	  }
	}
	
	// 导航操作统一封装
	const safeNavigate = (url: string) => {
	  if (uni?.navigateTo) {
	    uni.navigateTo({ url })
	  } else {
	    window.location.href = url
	  }
	}
	
	// 点击事件处理
	const onPlayList = (id: number) => {
	  safeNavigate(`/subPagesMusic/playlist/index?id=${id}`)
	}
	
	const onTopplaylist = (id: number) => {
	  safeNavigate(`/subPagesMusic/playlist/index?id=${id}`)
	}
	
	const onMv = (id: number) => {
	  try {
	    audioPlayer.stop?.()
	  } catch (e) {
	    console.warn('音频停止失败:', e)
	  }
	  safeNavigate(`/subPagesMusic/mvDataList/index?id=${id}`)
	}
	
	const onPlayerBar = () => {
	  const url = userStore.url || '/subPagesMusic/MusicHeader/index'
	  safeNavigate(url)
	}
</script>
<template>
	
	<scroll-view :show-scrollbar="false" :scroll-y='true'  direction='vertical' class="page-container">
	<!-- 页面容器 -->

	<view>
		<!-- 顶部导航栏 -->
		<view class="nav-bar">
			<text class="iconfont icon-menu"></text>
			<text class="title">发现音乐</text>
			<text class="iconfont icon-search"></text>
		</view>
		<searchVue></searchVue>
		<!-- 轮播图区域 -->
		<swiper class="banner-swiper" autoplay interval="3000" :circular='true'>
			<swiper-item v-for="(item, index) in musicDataList" :key="index">
				<image class="banner-image" :src="item?.pic" mode="aspectFill" />
			</swiper-item>
		</swiper>

		<!-- 推荐歌单 -->
		<view class="song-list-section">
			<view class="section-header">
				<text class="section-title">推荐歌单</text>
				<text class="more">更多  {{'>'}}</text>
			</view>

			<scroll-view :show-scrollbar="false" direction="horizontal" scroll-x class="horizontal-scroll">
							<view class="playlist-item" v-for="(item, index) in RecommendtList" :key="item.id"
												@click="onPlayList(item.id)">
												<image class="playlist-cover" :src="item?.coverImgUrl" />
												<text class="playlist-name">{{item?.name}}</text>
												<text class="play-count">▶ {{item?.playCount}}</text>
											</view>
						</scroll-view>
		</view>
		<view class="song-list-section">
			<view class="section-header">
				<text class="section-title">歌曲排行</text>
				<text class="more">更多  {{'>'}}</text>
			</view>

			<scroll-view :show-scrollbar="false" direction="horizontal"  scroll-x  class="horizontal-scroll">
				<view class="playlist-item" v-for="item in AllList" :key="item.id" @click='onTopplaylist(item.id)'>
					<view>
						<image class="playlist-cover" :src="item?.coverImgUrl" />
						<text class="playlist-name">{{item?.name}}</text>
						<text class="play-count">▶ {{item?.subscribedCount}}</text>
					</view>
				</view>
			</scroll-view>
		</view>
		<view class="song-list-section">
			<view class="section-header">
				<text class="section-title">视频MV</text>
				<text class="more">更多  {{'>'}}</text>
			</view>
			<scroll-view :show-scrollbar="false" direction="horizontal"  scroll-x  class="horizontal-scroll">
				<view class="playlist-item mv-item" style="width: 450rpx;height: 380rpx;" v-for="(item) in MvList" :key="item.id" @click="onMv(item.id)">
					<image class="playlist-cover" :src="item?.cover" style="width: 480rpx;height: 270rpx; margin: 0 auto;"  mode="aspectFill" />
					<text class="playlist-name">{{item?.name}}</text>
					<text class="play-count">▶ {{item?.playCount}}</text>
				</view>
			</scroll-view>
		</view>
		
		<!-- 底部播放控制栏 -->
		<view class="player-bar" @click="onPlayerBar">
			<image class="song-cover" src="/static/images/tabbar/music_normal.png" />
			<view class="song-info">
				<text class="song-title">{{userStore?.name}}</text>
				<text class="singer">{{userStore?.artist}}</text>
			</view>
			<text class="iconfont icon-play" style="color: #333;">▶</text>
							<text class="iconfont icon-list" style="color: #333;">█</text>
		</view>
	</view>
	
	</scroll-view>
	
	
</template>



<style lang="scss">
	@import './index.scss';
</style>